package org.study.daka.pksms;

import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.study.daka.pksms.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = MainActivity.class.getName();

    SmsObserver smsObserver;
    RecyclerView rc;
    Context context = this;

    ListView lv;

    EditText etKey;

    private final Handler smsHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Log.i(TAG, "handleMessage: " + msg.toString());
        }
    };

    class SmsObserver extends ContentObserver {
        public SmsObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange, Uri uri) {
            super.onChange(selfChange, uri);
            if (uri.toString().equals("content://sms/raw")) {
                return;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        smsObserver = new SmsObserver(smsHandler);
//        // 注册广播接受者
//        br = new SMSRecevier();
//        filter = new IntentFilter();
//        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
//        registerReceiver(br,filter);
        setContentView(R.layout.activity_main);
        initView(savedInstanceState);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        List<String> ids = new ArrayList<>();
        switch (id) {
            case R.id.button_clear:
                EditText key = findViewById(R.id.et_key);
                String str = key.getText().toString();
                Log.i(TAG, "onClick: 查找垃圾短信");
                resetRc(getSms(str));
                break;
            case R.id.button_one_key:
                for (int i = 0; i < rc.getChildCount(); i++) {
                    View view = rc.getChildAt(i);
                    CheckBox cb = view.findViewById(R.id.cb_rc_sms_item_id);
                    TextView tvid = view.findViewById(R.id.tv_rc_sms_item_id);
                    boolean checked = cb.isChecked();
                    if (checked) {
                        ids.add(tvid.getText().toString());
                    }
                }
                break;
        }
        if (!ids.isEmpty()) {
            //删除选中短信
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            AlertDialog dialog = builder.setTitle("确认删除短息").setMessage(String.format("确认删除这些信息吗")).
                    setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            for (int i = 0; i < ids.size(); i++) {
                                dropSms(ids.get(i));
                            }
                            resetRc(getSms(etKey.getText().toString()));
                        }
                    }).create();
            dialog.show();
        }
    }

    private void initView(Bundle savedInstanceState) {
        View view = findViewById(R.id.button_clear);
        view.setOnClickListener(this);
        rc = findViewById(R.id.rc_content);
        etKey = findViewById(R.id.et_key);

        LinearLayoutManager m = new LinearLayoutManager(context);
        rc.setLayoutManager(m);
        rc.setAdapter(new SMSContentAdapter(context, getSms("")));
        rc.addItemDecoration(new RecycleViewDivider(context, LinearLayoutManager.VERTICAL, R.drawable.dividerline));
    }

    private void resetRc(List<SMS> list) {
        if (rc != null) {
            rc.setAdapter(new SMSContentAdapter(context, list));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

//    class SMSRecevier extends BroadcastReceiver {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            StringBuilder content = new StringBuilder();//用于存储短信内容
//            String sender = null;//存储短信发送方手机号
//            Bundle bundle = intent.getExtras();//通过getExtras()方法获取短信内容
//            String format = intent.getStringExtra("format");
//            if (bundle != null) {
//                Object[] pdus = (Object[]) bundle.get("pdus");//根据pdus关键字获取短信字节数组，数组内的每个元素都是一条短信
//                for (Object object : pdus) {
//                    SmsMessage message=SmsMessage.createFromPdu((byte[])object,format);//将字节数组转化为Message对象
//                    sender = message.getOriginatingAddress();//获取短信手机号
//                    content.append(message.getMessageBody());//获取短信内容
//                }
//            }
//
//        }
//    }


    private Uri SMS_INBOX = Uri.parse("content://sms/");

    public List<SMS> getSms(String str) {
        ContentResolver cr = getContentResolver();
        String[] projection = new String[]{"_id", "address", "person", "body", "date", "type"};
        Cursor cur = cr.query(SMS_INBOX, projection, null, null, "date desc");
        if (null == cur) {
            Log.i("ooc", "************cur == null");
            return Collections.emptyList();
        }

        List<SMS> list = new ArrayList<>();
        while (cur.moveToNext()) {
            String number = cur.getString(cur.getColumnIndex("address"));//手机号
            String name = cur.getString(cur.getColumnIndex("person"));//联系人姓名列表
            String body = cur.getString(cur.getColumnIndex("body"));//短信内容
            String id = cur.getString(cur.getColumnIndex("_id"));
            String date = cur.getString(cur.getColumnIndex("date"));
            number = number == null ? "" : number;
            body = body == null ? "" : body;

            if (number.contains(str) || body.contains(str)) {
                //至此就获得了短信的相关的内容, 以下是把短信加入map中，构建listview,非必要。
                SMS sms = new SMS(id, number, body);
                sms.setDate(date);
                list.add(sms);
            }
            Log.d(TAG, "getSms: " + number + "|" + body);
        }
        return list;
    }

    public void dropSms(String id) {
        int delete = getContentResolver().delete(SMS_INBOX, "id=?", new String[]{id});
        Log.i(TAG, "dropSms: 删除短信:"+id+",结果:"+delete);
    }

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    class SMS {
        private String id;
        private String num;
        private String content;
        private String date;

        public SMS(String id, String num, String content) {
            this.num = num;
            this.content = content;
            this.id = id;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getDate() {
            return date;
        }

        public void setDate(String date) {
            try {
                Long aLong = Long.valueOf(date);
                this.date = sdf.format(new Date(aLong));
            }catch (Exception ex){
                this.date = date;
            }
        }

        public String getNum() {
            return num;
        }

        public void setNum(String num) {
            this.num = num;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }
    }
}